import Vue from "vue";
import VueRouter from "vue-router";
import routes from "./router";
import { getToken } from "@/utils";
import { Message } from "element-ui";
import store from "@/store";
Vue.use(VueRouter);
const originalPush = VueRouter.prototype.push;
const originalReplace = VueRouter.prototype.replace;
VueRouter.prototype.push = function (to, onComplete, onAbort) {
  onComplete && onAbort
    ? originalPush.call(this, to, onComplete, onAbort)
    : originalPush.call(
        this,
        to,
        () => {},
        () => {}
      );
};
VueRouter.prototype.replace = function (to, onComplete, onAbort) {
  onComplete && onAbort
    ? originalReplace.call(this, to, onComplete, onAbort)
    : originalReplace.call(
        this,
        to,
        () => {},
        () => {}
      );
};
//试一试封装
/*function enhancementMethod(originalTarget, methodName) {
  const originalMethod = originalTarget.prototype[methodName];
  originalTarget.prototype[methodName] = function (to, onComplete, onAbort) {
    onComplete && onAbort
      ? originalMethod.call(this, to, onComplete, onAbort)
      : originalMethod.call(
          this,
          to,
          () => {},
          () => {}
        );
  };
}
enhancementMethod(VueRouter, "push");
enhancementMethod(VueRouter, "replace");*/
const loginList = ["/trade", "/pay", "/paysuccess", "/center"];
const router = new VueRouter({
  mode: "history",
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) return savedPosition;
    else
      return {
        y: 0,
      };
  },
});
router.beforeEach(async (to, from, next) => {
  const nickName = store.state.user.userInfo.nickName;
  // to and from are both route objects. must call `next`.
  if (getToken()) {
    if (to.path === "/login") next(from.path);
    else {
      if (nickName) next();
      else {
        try {
          await store.dispatch("getUserInfo");
          next();
        } catch (error) {
          Message.warning(error);
          localStorage.removeItem("TOKEN");
          next("/login");
        }
      }
    }
  } else {
    if (loginList.includes(to.path)) next("/login");
    else next();
  }
});
export default router;
